package com.zhb.controller;


import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.zhb.entity.Product;
import com.zhb.service.IProductService;
import io.seata.core.context.RootContext;
import lombok.AllArgsConstructor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.zhb.responvo.ResponseInfo;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zhb
 * @since 2021-09-09
 */
@RestController
@AllArgsConstructor
@Slf4j
public class ProductController {

    private final IProductService productService;

    @RequestMapping("product/getById")
    @SentinelResource(value = "getProductById", blockHandler = "handleException")
    public ResponseInfo<Product> getById(Integer productId, ResponseInfo<Product> responseInfo) {
        Product byId = productService.getById(productId);
        responseInfo.setData(byId);
        return responseInfo;
    }

    @RequestMapping("product/deduct")
    public ResponseInfo deduct(String productCode,Integer count){
        ResponseInfo responseInfo = new ResponseInfo();
        String xid = RootContext.getXID();
        log.error(xid);
        int i = productService.reduceProduct(productCode, count);
        if (i == 0){
            throw new RuntimeException("库存扣除异常！！！！！");
        }
        return responseInfo;
    }

    public ResponseInfo<Product> handleException(Integer productId, ResponseInfo<Product> responseInfo,BlockException exception) {
        log.info("异常信息是：----{}", exception.getMessage());
        responseInfo.setCode(500);
        responseInfo.setMessage("请注意限流啦！！！");
        return responseInfo;
    }
}
